﻿using Digitalmes.Model;
using Digitalmes.Model.EquipmentManagement;
using Digitalmes.Models;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using System;

namespace Digitalmes.Extensions
{
    public static class EquipmentTagExtensions
    {
        public static SysTag ToTag(this EquipmentTag equipmentTag,string groupName)
        {
            if (equipmentTag == null)
                throw new ArgumentNullException(nameof(equipmentTag));

            // 将 TagDataTypeEnum 转换为 TypeCode
            TypeCode typeCode = ConvertTagDataTypeToTypeCode(equipmentTag.DataType);

            var stag = new SysTag(
                equipmentTag.ID,
                equipmentTag.TagName,
                equipmentTag.Address,
                equipmentTag.EquipmentId,
                equipmentTag.Description,
                equipmentTag.TagType,
                equipmentTag.DataType,
                equipmentTag.ScanRate,
                equipmentTag.GroupType,
                equipmentTag.AccessMode,
                equipmentTag.DriverType,
                equipmentTag.UpLimit,
                equipmentTag.LowerLimit,
                equipmentTag.ActiveLimit,
                equipmentTag.EquipCode,
                 typeCode,
                 groupName
            );
           
            return stag;
        }

        private static TypeCode ConvertTagDataTypeToTypeCode(TagDataTypeEnum dataType)
        {
            // 根据你的实际 TagDataTypeEnum 定义进行映射
            return dataType switch
            {
                TagDataTypeEnum.Sys_Bit => TypeCode.Boolean,
                TagDataTypeEnum.Sys_Byte => TypeCode.Byte,
                TagDataTypeEnum.Sys_Int => TypeCode.Int16,
                TagDataTypeEnum.Sys_Word => TypeCode.UInt16,
                TagDataTypeEnum.Sys_DInt => TypeCode.Int32,
                TagDataTypeEnum.Sys_DWord => TypeCode.UInt32,
              
                TagDataTypeEnum.Sys_Real => TypeCode.Single,
                TagDataTypeEnum.Sys_LReal => TypeCode.Double,
                TagDataTypeEnum.Sys_String=> TypeCode.String,
                
                _ => TypeCode.Object
            };
        }

        private static object GetDefaultValue(TypeCode typeCode)
        {
            return typeCode switch
            {
                TypeCode.Boolean => false,
                TypeCode.Byte => (byte)0,
                TypeCode.Int16 => (short)0,
                TypeCode.UInt16 => (ushort)0,
                TypeCode.Int32 => 0,
                TypeCode.UInt32 => 0u,
                TypeCode.Int64 => 0L,
                TypeCode.UInt64 => 0UL,
                TypeCode.Single => 0f,
                TypeCode.Double => 0d,
                TypeCode.String => string.Empty,
           
                _ => null
            };
        }
    }
}